import delegates from '../../utils/delegates'
import is from '../../utils/is'

class Resize {
  constructor (player) {
    this.player = player

    delegates(this.player, this)
      .method('getWidth')
      .method('getHeight')
      .method('resize')

    this.setWidth()
    if (!this.setAspect()) {
      this.setHeight()
    }
  }

  getWidth () {
    return this.player.dom.container.getBoundingClientRect().width
  }

  getHeight () {
    return this.player.dom.container.getBoundingClientRect().height
  }

  resize (width, height) {
    width = this.setWidth(width)
    height = this.setHeight(height)
    this.removeAspect()
    this.player.trigger('resize', {type: 'resize', width, height})
  }

  setWidth (width) {
    let cssWidth = (width = width || this.player._config.width)
    if (is('number', cssWidth)) {
      cssWidth = width + 'px'
    }
    this.player.dom.container.style.width = cssWidth
    return width
  }

  setHeight (height) {
    let cssHeight = (height = height || this.player._config.height)
    if (is('number', cssHeight)) {
      cssHeight = height + 'px'
    }
    this.player.dom.container.style.height = cssHeight
    return height
  }

  setAspect () {
    const {aspectratio} = this.player._config
    const aspects = aspectratio
      .split(':')
      .map(v => +v)
      .filter(v => !!v && v > 0)
    if (aspects.length === 2) {
      const percentage = (aspects[1] / aspects[0]) * 100 + '%'
      this.player.dom.aspect.style.paddingTop = percentage
      this.player.dom.container.classList.add(
        `${this.player._baseClass}-aspect-mode`
      )
      this.setHeight('auto')
      return true
    }
    return false
  }

  removeAspect () {
    this.player.dom.aspect.style.paddingTop = 0
    this.player.dom.container.classList.remove(
      `${this.player._baseClass}-aspect-mode`
    )
  }

  // on resize
}

export default Resize
